package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.service.UserService;
import com.yuelao.yuelao_backend.service.security.CustomUserDetails;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.Collections;

/**
 * Spring Security UserDetailsService 实现
 * 用于根据用户名（手机号）加载用户信息
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 在我们的应用中，用户名就是手机号
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(User::getId, User::getPhone, User::getNickname, User::getPassword, User::getStatus);
        queryWrapper.eq(User::getPhone, username);
        User user = userService.getOne(queryWrapper);

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            // 密码未设置，理论上不应该发生，但作为安全检查
            throw new UsernameNotFoundException("用户密码信息异常: " + username);
        }

        // 返回我们自定义的 CustomUserDetails 对象
        // 这里可以根据需要加载用户的角色和权限
        // 为了简化，我们暂时给所有用户一个 "ROLE_USER" 的默认权限
        return new CustomUserDetails( user, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
        );
    }
}